"""
@author: wangkang
@contact: wangkang@autobio.com.cn
@file: parse_json_entity_relation.py
@time: 2020/1/22 15:15
@desc: 解析doccano的标注数据
"""
import os
import re
import json
from functools import reduce
base_path = os.path.dirname(os.path.dirname(__file__))
with open(os.path.join(base_path,'data/file.json'), 'r', encoding='utf8') as file:
    with open(os.path.join(base_path,'data/entries_relation_have.csv'), 'a+', encoding='utf8') as f1, \
            open(os.path.join(base_path,'data/entries_relation_belong.csv'), 'a+', encoding='utf8') as f2, \
            open(os.path.join(base_path,'data/entries_relation_attribute.csv'), 'a+', encoding='utf8') as f3, \
            open(os.path.join(base_path,'data/entries_relation_method.csv'), 'a+', encoding='utf8') as f4:
        header = 'entry1,relation,entry2'
        f1.write(header + '\n')
        f2.write(header + '\n')
        f3.write(header + '\n')
        f4.write(header + '\n')
        for idx, line in enumerate(file.readlines()):
            # 目前，仅对前70个样本进行打标处理
            if idx < 70:
                dic = json.loads(line)

                # 构造 设备类型与 部位的实体关系
                if '设备类型' and '部位' in str(dic['labels']):
                    dic['labels'].sort(key=lambda x: x[1])
                    entry1_list = []
                    entry2_list = []
                    relation_list = []
                    for i in range(len(dic['labels'])):
                        entry_start, entry_end, entry_type = dic['labels'][i]
                        entry_name = dic['text'][entry_start: entry_end]
                        if entry_type == '部位':
                            entry2_list.append(entry_name)
                            entry2_list = list(set(entry2_list))
                        if entry_type == '设备类型':
                            entry1_list.append(entry_name)
                            entry1_list = list(set(entry1_list))
                    for entry1 in entry1_list:
                        for entry2 in entry2_list:
                            entries_relation = entry1 + ',' + 'have' + ',' + entry2
                            f1.write(entries_relation + '\n')

                # 构造部位与子部位的实体关系
                if '子部位' and '部位' in str(dic['labels']):
                    dic['labels'].sort(key=lambda x: x[1])
                    new_list = reduce(lambda x, y: x + y, dic['labels'])
                    final = []
                    for i in new_list:
                        if isinstance(i, int):
                            stk_code = str(i).zfill(3)
                            final.append(stk_code)
                        else:
                            final.append(i)
                    string = [str(i) for i in final]
                    string = ''.join(string)
                    # 正则匹配【部位+子部位】的位置索引
                    match_obj = re.findall(r'\S{6}\部位\S{6}\子部位', string)
                    for i in range(len(match_obj)):
                        entry_1 = dic['text'][int(match_obj[i][0:3]): int(match_obj[i][3:6])]
                        entry_2 = dic['text'][int(match_obj[i][8:11]):int(match_obj[i][11:14])]
                        entries_relation = entry_2 + ',' + 'belong to' + ',' + entry_1
                        f2.write(entries_relation + '\n')

                # 构造部位与现象的实体关系
                if '具体表现' and '部位' in str(dic['labels']):
                    dic['labels'].sort(key=lambda x: x[1])
                    new_list = reduce(lambda x, y: x + y, dic['labels'])
                    final = []
                    for i in new_list:
                        if isinstance(i, int):
                            stk_code = str(i).zfill(3)
                            final.append(stk_code)
                        else:
                            final.append(i)
                    string = [str(i) for i in final]
                    string = ''.join(string)
                    # 正则匹配【部位+具体表现】的位置索引
                    match_obj = re.findall(r'\S{6}\部位\S{6}\具体表现', string)
                    for i in range(len(match_obj)):
                        entry_1 = dic['text'][int(match_obj[i][0:3]): int(match_obj[i][3:6])]
                        entry_2 = dic['text'][int(match_obj[i][8:11]):int(match_obj[i][11:14])]
                        entries_relation = entry_2 + ',' + 'abnormal attribute' + ',' + entry_1
                        f3.write(entries_relation + '\n')

                # 构造部位与具体方法的实体关系
                if '部位' and '具体方法' in str(dic['labels']):
                    dic['labels'].sort(key=lambda x: x[1])
                    new_list = reduce(lambda x, y: x + y, dic['labels'])
                    final = []
                    for i in new_list:
                        if isinstance(i, int):
                            stk_code = str(i).zfill(3)
                            final.append(stk_code)
                        else:
                            final.append(i)
                    string = [str(i) for i in final]
                    string = ''.join(string)
                    # 正则匹配【具体方法+部位】的位置索引
                    match_obj = re.findall(r'\S{6}\具体方法\S{6}\部位', string)
                    for i in range(len(match_obj)):
                        entry_1 = dic['text'][int(match_obj[i][0:3]): int(match_obj[i][3:6])]
                        entry_2 = dic['text'][int(match_obj[i][10:13]):int(match_obj[i][13:16])]
                        entries_relation = entry_2 + ',' + 'method' + ',' + entry_1
                        f4.write(entries_relation + '\n')
                    # 正则匹配【具体方法+部位+部位】的位置索引
                    match_obj = re.findall(r'\S{6}\具体方法\S{6}\部位\S{6}部位', string)
                    for i in range(len(match_obj)):
                        entry_1 = dic['text'][int(match_obj[i][0:3]): int(match_obj[i][3:6])]
                        entry_2 = dic['text'][int(match_obj[i][10:13]):int(match_obj[i][13:16])]
                        entry_3 = dic['text'][int(match_obj[i][18:21]):int(match_obj[i][21:24])]
                        entries_relation = entry_2 + ',' + 'method' + ',' + entry_1
                        f4.write(entries_relation + '\n')
